"""
监控指标服务模块

该模块提供监控指标相关的业务逻辑处理，包括接收agent上报的监控数据、存储到数据库等。
"""

from typing import Dict, Any, Optional
from app.crud.metric import create_metric
from app.crud.machine import get_machine_by_ip, update_machine_metrics, get_machine_by_id, update_machine
from app.schemas.metric import MetricCreate
from sqlalchemy.orm import Session
from app.core.performance_monitor import monitor_db_performance
import json
import logging

logger = logging.getLogger(__name__)

class MetricService:
    """监控指标服务类"""
    
    def __init__(self, db: Session):
        self.db = db
    
    @monitor_db_performance("process_agent_data")
    def process_agent_data(self, agent_data: Dict[str, Any]) -> bool:
        """处理来自agent的监控数据
        
        Args:
            agent_data (Dict[str, Any]): 来自agent的监控数据
            
        Returns:
            bool: 处理是否成功
        """
        try:
            # 获取系统信息
            system_info = agent_data.get("system", {})
            ip_address = system_info.get("ip_address")
            
            # 根据IP查找机器
            machine = get_machine_by_ip(self.db, ip_address)
            if not machine:
                logger.warning(f"未找到IP地址为 {ip_address} 的机器")
                return False
            
            # 更新机器的监控指标
            cpu_percent = agent_data.get("cpu", {}).get("cpu_percent", 0)
            memory_info = agent_data.get("memory", {})
            memory_percent = memory_info.get("memory_percent", 0)
            
            # 计算磁盘使用率（取所有分区的平均值）
            disk_info = agent_data.get("disk", {}).get("partitions", [])
            disk_percent = 0
            if disk_info:
                total_percent = sum(partition.get("percent", 0) for partition in disk_info)
                disk_percent = total_percent / len(disk_info)
            
            # 更新机器指标
            update_machine_metrics(
                self.db, 
                int(str(machine.id)), 
                int(cpu_percent), 
                int(memory_percent), 
                int(disk_percent)
            )
            
            # 创建详细的监控指标记录
            disk_info_json = json.dumps(disk_info) if disk_info else None
            
            cpu_info = agent_data.get("cpu", {})
            network_info = agent_data.get("network", {})
            
            metric_data = MetricCreate(
                machine_id=int(str(machine.id)),
                cpu_percent=cpu_percent,
                cpu_count=cpu_info.get("cpu_count"),
                cpu_count_logical=cpu_info.get("cpu_count_logical"),
                cpu_freq_current=cpu_info.get("cpu_freq", {}).get("current"),
                memory_total=memory_info.get("memory_total"),
                memory_available=memory_info.get("memory_available"),
                memory_percent=memory_percent,
                memory_used=memory_info.get("memory_used"),
                swap_total=memory_info.get("swap_total"),
                swap_used=memory_info.get("swap_used"),
                swap_percent=memory_info.get("swap_percent"),
                disk_info=disk_info_json,
                network_bytes_sent=network_info.get("bytes_sent"),
                network_bytes_recv=network_info.get("bytes_recv"),
                network_packets_sent=network_info.get("packets_sent"),
                network_packets_recv=network_info.get("packets_recv")
            )
            
            # 保存监控指标
            create_metric(self.db, metric_data)
            
            logger.info(f"成功处理来自 {ip_address} 的监控数据")
            return True
            
        except Exception as e:
            logger.error(f"处理agent数据时发生错误: {str(e)}")
            return False

    @monitor_db_performance("get_agent_config")
    def get_agent_config(self, machine_ip: str) -> Optional[Dict[str, Any]]:
        """获取agent配置信息
        
        Args:
            machine_ip (str): 机器IP地址
            
        Returns:
            Optional[Dict[str, Any]]: 配置信息字典
        """
        try:
            # 根据IP查找机器
            machine = get_machine_by_ip(self.db, machine_ip)
            if not machine:
                logger.warning(f"未找到IP地址为 {machine_ip} 的机器")
                return None
            
            # 获取配置信息
            monitor_config = str(machine.monitor_config) if machine.monitor_config is not None else ""
            if monitor_config != "":
                try:
                    config_dict = json.loads(monitor_config)
                    config_dict["machine_id"] = int(str(machine.id))
                    logger.info(f"成功获取机器 {machine_ip} 的配置信息")
                    return config_dict
                except json.JSONDecodeError:
                    logger.error(f"解析机器 {machine_ip} 的配置信息失败: {monitor_config}")
                    # 返回默认配置
                    pass
            
            # 返回默认配置
            config_dict = {
                "machine_id": int(str(machine.id)),
                "interval": 30,
                "collect_system_info": True,
                "collect_cpu_info": True,
                "collect_memory_info": True,
                "collect_disk_info": True,
                "collect_network_info": True,
                "collect_process_info": False,
                "collect_log_info": False,
                "collect_database_info": False,
                "log_paths": [],
                "database_configs": [],
                "port_list": [],
                "process_names": []  # 添加process_names字段
            }
            
            logger.info(f"使用默认配置为机器 {machine_ip}")
            return config_dict
            
        except Exception as e:
            logger.error(f"获取agent配置时发生错误: {str(e)}")
            return None

    @monitor_db_performance("update_agent_config")
    def update_agent_config(self, machine_id: int, config: Dict[str, Any]) -> bool:
        """更新agent配置信息
        
        Args:
            machine_id (int): 机器ID
            config (Dict[str, Any]): 配置信息
            
        Returns:
            bool: 更新是否成功
        """
        try:
            # 获取机器
            machine = get_machine_by_id(self.db, machine_id)
            if not machine:
                logger.warning(f"未找到ID为 {machine_id} 的机器")
                return False
            
            # 确保所有需要的字段都存在
            required_fields = [
                "interval", "collect_system_info", "collect_cpu_info", 
                "collect_memory_info", "collect_disk_info", "collect_network_info",
                "collect_process_info", "collect_log_info", "collect_database_info",
                "log_paths", "database_configs", "port_list", "process_names"
            ]
            
            for field in required_fields:
                if field not in config:
                    # 设置默认值
                    if field == "interval":
                        config[field] = 30
                    elif field.startswith("collect_"):
                        config[field] = False if field == "collect_process_info" else True
                    elif field in ["log_paths", "database_configs", "port_list", "process_names"]:
                        config[field] = []
            
            # 更新机器的监控配置
            config_json = json.dumps(config)
            update_machine(self.db, machine_id, {"monitor_config": config_json})
            
            logger.info(f"成功更新机器 {machine_id} 的配置")
            return True
        except Exception as e:
            logger.error(f"更新agent配置时发生错误: {str(e)}")
            return False